import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sptapp/config/const.dart';


class LineChartSample4 extends StatefulWidget {
  final List datas;
  final List values;
  final int selType;
  final int selIndex;
  final String unit;
  const LineChartSample4({super.key, required this.datas, required this.values, required this.unit, required this.selType, required this.selIndex,});

  @override
  State<LineChartSample4> createState() => _LineChartSample4State();
}

class _LineChartSample4State extends State<LineChartSample4> {

  Color mainLineColor = Color.fromRGBO(255, 255, 255, 0);
  List<int> showingTooltipOnSpots = [];

  List<FlSpot> _spots = [];

  double maxValue = 0;
  double minValue = 0;
  double aavgValue = 0;
  double bavgValue = 0;
  double bSpace = 1;


  Widget bottomTitleWidgets(double value, TitleMeta meta) {
    if(widget.datas.isEmpty){
      return Container();
    }
    int length = widget.datas.length ~/ 4;
    if(value.toInt() == length || value.toInt() == length *2 || value.toInt() == length *3){
      return SideTitleWidget(
        axisSide: meta.axisSide,
        space: 12,
        angle: 0,
        child: Text(
          widget.datas.isNotEmpty? widget.datas[value.toInt()]:'',
          style: TextStyle(
            fontSize: 12,
            color: Color.fromRGBO(255, 255, 255, 0.3),
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    }
    return Container();
  }

  Widget rightTitleWidgets(double value, TitleMeta meta){
    if( value == 0){
      return SideTitleWidget(
        axisSide: meta.axisSide,
        space: 10,
        angle: 0,
        child: Container(
          child: Text(
            '$value${widget.unit}',
            style: TextStyle(
              fontSize: 10,
              color: Color.fromRGBO(255, 255, 255, 0.3),
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      );
    }
    return Container();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getSpots();
  }

  _getSpots(){
    _spots.clear();
    if(widget.datas.isEmpty){
      return;
    }
    // if(widget.datas.isNotEmpty){
    //   bSpace = widget.datas.length / 4;
    // }
    for(int i=0; i<widget.datas.length; i++ ){
      if(i > widget.values.length-1){
        _spots.add(FlSpot(double.parse(i.toString()), 0));
      }else {
        _spots.add(FlSpot(double.parse(i.toString()), double.parse(widget.values[i].toString())));
        if(double.parse(widget.values[i].toString()) > maxValue){
          maxValue = double.parse(widget.values[i].toString());
        }
        if(double.parse(widget.values[i].toString()) < minValue){
          minValue = double.parse(widget.values[i].toString());
        }
      }
    }

    if(widget.selType == 0 || widget.selType == 4){
      // if(maxValue.abs() > minValue.abs()){
      //   minValue  = -maxValue.abs();
      // }else if(maxValue.abs() < minValue.abs()){
      //   maxValue = minValue.abs();
      // }
    }else if(widget.selType == 1){
      maxValue = 100;
      minValue = 0;
    }else{
      minValue = 0;
    }

    aavgValue = maxValue/2;
    bavgValue = minValue/2;
    if(mounted){
      setState(() {});
    }
  }

  @override
  void didUpdateWidget(covariant LineChartSample4 oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    maxValue = 0;
    minValue = 0;
    aavgValue = 0;
    bavgValue = 0;
    showingTooltipOnSpots.clear();
    _getSpots();
  }
  
  @override
  Widget build(BuildContext context) {
    const cutOffYValue = 0.0;
    final lineBarsData = [
      LineChartBarData(
        spots: _spots,
        showingIndicators: showingTooltipOnSpots,
        isCurved: false,
        barWidth:  0.w,
        color: widget.selType ==1? Color(0xff00ff01) : widget.selType ==2 || widget.selType == 3? themeColor:mainLineColor,
        belowBarData: BarAreaData(
            show: true,
            cutOffY: cutOffYValue,
            applyCutOffY: true,
            gradient:  widget.selType == 2?  LinearGradient(
              colors: [
                Color.fromRGBO(205, 150, 7, 0.1),
                Color.fromRGBO(103, 75, 4, 1),
              ],
              begin: Alignment.bottomCenter,
              end: Alignment.topCenter,
            ) : widget.selType != 1? LinearGradient(
              colors: [
                Color.fromRGBO(35, 50, 146, 1),
                Color.fromRGBO(60, 85, 248, 0.1),
              ],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ):LinearGradient(
              colors: [
                Color.fromRGBO(0, 153, 1, 0.5),
                Color.fromRGBO(0, 255, 1, 0.1),
              ],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            )
        ),
        aboveBarData: BarAreaData(
          show: true,
          cutOffY: cutOffYValue,
          applyCutOffY: true,
          gradient: LinearGradient(
            colors: [
              Color.fromRGBO(205, 150, 7, 0.1),
              Color.fromRGBO(103, 75, 4, 1),
            ],
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
          ),

        ),
        dotData:  const FlDotData(
          show: false,
        ),
      ),
    ];
    final tooltipsOnBar = lineBarsData[0];
    final ExtraLinesData extraLinesData;
    print('maxvalue==== $maxValue');
    if(widget.selType ==0 || widget.selType == 4){
      extraLinesData = ExtraLinesData(
        horizontalLines: [
          HorizontalLine(
              y: 0,
              color: Color.fromRGBO(255, 255, 255, 0.3),
              strokeWidth: 1,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '0 ${widget.unit}',
              ),
              dashArray: [2,2]
          ),
          HorizontalLine(
            y: maxValue,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '$maxValue ${widget.unit}',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.3),
            strokeWidth: 0.5,
          ),
          HorizontalLine(
            y: maxValue/2,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.1),
            strokeWidth: 0.5,
          ),
          HorizontalLine(
            y: minValue/2,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.1),
            strokeWidth: 0.5,
          ),
          HorizontalLine(
            y: minValue,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '${minValue.toString().replaceAll("-", "")} ${widget.unit}',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.3),
            strokeWidth: 0.5,
          ),
        ],
        verticalLines: maxValue == 0 && minValue == 0? []: [
            VerticalLine(
              x: widget.datas.length /4,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 2,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 3,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
          ]
      );
    }
    else if(widget.selType == 1){
      extraLinesData = ExtraLinesData(
        horizontalLines: [
          HorizontalLine(
            y: maxValue,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '$maxValue ${widget.unit}',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.3),
            strokeWidth: 0.5,
          ),
          HorizontalLine(
            y: 75,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.1),
            strokeWidth: 0.1,
          ),
          HorizontalLine(
            y: 50,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '50 ${widget.unit}',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.3),
            strokeWidth: 0.5,
            dashArray: [2,2]
          ),
          HorizontalLine(
            y: 25,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.1)
              ),
              labelResolver: (line) => '',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.1),
            strokeWidth: 0.1,
          ),
          HorizontalLine(
            y: minValue,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '$minValue ${widget.unit}',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.3),
            strokeWidth: 0.5,
          ),
        ],
        verticalLines: [
          VerticalLine(
            x: widget.datas.length /4,
            color: Color.fromRGBO(255, 255, 255, 0.1),
            strokeWidth: 2,
            dashArray: [2, 2],
            label: VerticalLineLabel(
              show: false,
              alignment: Alignment.bottomRight,
              padding: const EdgeInsets.only(left: 5, bottom: 5),
              direction: LabelDirection.vertical,
              labelResolver: (line) => 'V: ${line.x}',
            ),
          ),
          VerticalLine(
            x: widget.datas.length /4 * 2,
            color: Color.fromRGBO(255, 255, 255, 0.1),
            strokeWidth: 2,
            dashArray: [2, 2],
            label: VerticalLineLabel(
              show: false,
              alignment: Alignment.bottomRight,
              padding: const EdgeInsets.only(left: 5, bottom: 5),
              direction: LabelDirection.vertical,
              labelResolver: (line) => 'V: ${line.x}',
            ),
          ),
          VerticalLine(
            x: widget.datas.length /4 * 3,
            color: Color.fromRGBO(255, 255, 255, 0.1),
            strokeWidth: 2,
            dashArray: [2, 2],
            label: VerticalLineLabel(
              show: false,
              alignment: Alignment.bottomRight,
              padding: const EdgeInsets.only(left: 5, bottom: 5),
              direction: LabelDirection.vertical,
              labelResolver: (line) => 'V: ${line.x}',
            ),
          ),
        ]
      );
    }else{
      extraLinesData = ExtraLinesData(
        horizontalLines: [
          HorizontalLine(
            y: maxValue,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '$maxValue ${widget.unit}',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.3),
            strokeWidth: 0.5,
          ),
          HorizontalLine(
              y: maxValue/4*3,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 0.1,
              label: HorizontalLineLabel(
                show: false,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '',
              ),

          ),
          HorizontalLine(
              y: aavgValue,
              color: Color.fromRGBO(255, 255, 255, 0.3),
              strokeWidth: 1,
              label: HorizontalLineLabel(
                show: true,
                alignment: Alignment.topRight,
                padding: const EdgeInsets.only(right: 5, bottom: 5),
                style:  TextStyle(
                    fontSize: 20.sp,
                    fontWeight: FontWeight.w400,
                    color: Color.fromRGBO(255, 255, 255, 0.5)
                ),
                labelResolver: (line) => '${aavgValue.toString().replaceAll("-", "")} ${widget.unit}',
              ),
              dashArray: [2,2]
          ),
          HorizontalLine(
            y: maxValue/4,
            color: Color.fromRGBO(255, 255, 255, 0.1),
            strokeWidth: 0.1,
            label: HorizontalLineLabel(
              show: false,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '',
            ),

          ),
          HorizontalLine(
            y: minValue,
            label: HorizontalLineLabel(
              show: true,
              alignment: Alignment.topRight,
              padding: const EdgeInsets.only(right: 5, bottom: 5),
              style:  TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Color.fromRGBO(255, 255, 255, 0.5)
              ),
              labelResolver: (line) => '$minValue ${widget.unit}',
            ),
            color: Color.fromRGBO(255, 255, 255, 0.3),
            strokeWidth: 0.5,
          ),
        ],
          verticalLines: maxValue != 0? [
            VerticalLine(
              x: widget.datas.length /4,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 2,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
            VerticalLine(
              x: widget.datas.length /4 * 3,
              color: Color.fromRGBO(255, 255, 255, 0.1),
              strokeWidth: 2,
              dashArray: [2, 2],
              label: VerticalLineLabel(
                show: false,
                alignment: Alignment.bottomRight,
                padding: const EdgeInsets.only(left: 5, bottom: 5),
                direction: LabelDirection.vertical,
                labelResolver: (line) => 'V: ${line.x}',
              ),
            ),
          ]:[]
      );
    }
    return AspectRatio(
      aspectRatio: 1,
      child: Padding(
        padding: EdgeInsets.only(
          left: 0,
          right: 0,
          top: 20,
          bottom: 0,
        ),
        child: widget.datas.isNotEmpty? LineChart(
          LineChartData(
            showingTooltipIndicators: showingTooltipOnSpots.map((index) {
              return ShowingTooltipIndicators([
                LineBarSpot(
                  tooltipsOnBar,
                  lineBarsData.indexOf(tooltipsOnBar),
                  tooltipsOnBar.spots[index],
                ),
              ]);
            }).toList(),
            maxY: maxValue,
            minY: minValue,
            lineTouchData: LineTouchData(
              enabled: true,
              touchTooltipData: LineTouchTooltipData(
                getTooltipColor: (touchedSpot) => Color(0xff141414),
                fitInsideHorizontally: true,
                fitInsideVertically: true,
                getTooltipItems: (touchedSpots) {
                  return touchedSpots.map((LineBarSpot touchedSpot) {
                    final textStyle = TextStyle(
                      color: Color.fromRGBO(255, 255, 255, 0.5),
                      fontWeight: FontWeight.bold,
                      fontSize: 18.sp,
                    );
                    return LineTooltipItem(
                      '',
                      textStyle,
                      textAlign: TextAlign.left,
                      children: [
                        TextSpan(
                            text: '${widget.datas[touchedSpot.x.toInt()]}\n',
                            style: TextStyle(
                              color: Color.fromRGBO(255, 255, 255, 0.5),
                              fontWeight: FontWeight.bold,
                              fontSize: 20.sp,
                            )
                        ),
                        TextSpan(
                          text: '${touchedSpot.y.toString().replaceAll("-", "")}${widget.unit}',
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 20.sp,
                          )
                        ),
                      ]
                    );
                  }).toList();
                },
              ),
              touchCallback: (FlTouchEvent event, LineTouchResponse? response){
                if (response == null || response.lineBarSpots == null) {
                  return;
                }
                if (event is FlTapUpEvent) {
                  final spotIndex = response.lineBarSpots!.first.spotIndex;
                  setState(() {
                  if (showingTooltipOnSpots.contains(spotIndex)) {
                    showingTooltipOnSpots.remove(spotIndex);
                  } else {
                    showingTooltipOnSpots.clear();
                    showingTooltipOnSpots.add(spotIndex);
                  }
                  });
                }
              },
              getTouchedSpotIndicator:
                  (LineChartBarData barData, List<int> spotIndexes) {
                return spotIndexes.map((index) {
                  return TouchedSpotIndicatorData(
                    const FlLine(
                        color: Colors.white,
                        strokeWidth: 1,
                        dashArray: [2,2]
                    ),
                    FlDotData(
                      show: true,
                      getDotPainter: (spot, percent, barData, index) =>
                          FlDotCirclePainter(
                            radius: 2,
                            color: Colors.white,
                            strokeWidth: 2,
                            strokeColor: Colors.white,
                          ),
                    ),
                  );
                }).toList();
              },
              handleBuiltInTouches: false,
            ),
            extraLinesData: extraLinesData,
            lineBarsData: lineBarsData,
            titlesData: FlTitlesData(
              show: true,
              topTitles: const AxisTitles(
                sideTitles: SideTitles(showTitles: false),
              ),
              rightTitles: AxisTitles(
                sideTitles: SideTitles(
                  showTitles: false,
                  reservedSize: 0,
                  interval: 5,
                  getTitlesWidget: rightTitleWidgets,
                  minIncluded: false,
                  maxIncluded: false
                ),
              ),
              bottomTitles: AxisTitles(
                sideTitles: SideTitles(
                  showTitles: true,
                  reservedSize: 26,
                  interval: bSpace,
                  maxIncluded: false,
                  minIncluded: false,
                  getTitlesWidget: bottomTitleWidgets,
                ),

              ),
              leftTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: false,
                  )
              ),
            ),
            borderData: FlBorderData(
              show: false,
            ),
            gridData: FlGridData(
              show: true,
              drawVerticalLine: false,
              drawHorizontalLine: false,
            ),
          ),
        ):Container(),
      ),
    );
  }
}

